package com.apobates.forum.trident.controller.admin;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.trident.controller.form.TopicCategoryForm;
import com.apobates.forum.core.api.service.BoardTopicCategoryIndexService;
import com.apobates.forum.core.api.service.TopicCategoryService;
import com.apobates.forum.core.entity.TopicCategory;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;
/**
 * 话题类型控制器
 * 
 * @author xiaofanku
 * @since 20190407
 */
@Controller
@RequestMapping(value = "/admin/topic/category")
public class AdminTopicCategoryController {
	@Autowired
	private TopicCategoryService topicCategoryService;
	@Autowired
	private BoardTopicCategoryIndexService boardTopicCategoryIndexService;
	@Value("${site.pageSize}")
	private int pageSize;
	
	@GetMapping(path="/")
	public String listPage(@RequestParam(value = "p", required = false, defaultValue = "1") int page, HttpServletRequest request, Model model) {
		FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/admin/topic/category/").addPageSize("number", pageSize);
		Pageable pr = new PageRequest(page, fpbuild.getPageSize());
		Page<TopicCategory> rs = topicCategoryService.getAll(pr);
		model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
		model.addAttribute("pageData", pr.toData(fpbuild, rs.getTotalElements()));
		return "admin/topic_category/index";
	}
	//增加|编辑
	@GetMapping(path="/edit")
	public String editForm(
			@RequestParam(name="id", required=false, defaultValue="0") int id,
			HttpServletRequest request, 
			Model model){
		TopicCategoryForm form = new TopicCategoryForm();
		TopicCategory tc = topicCategoryService.get(id).orElse(new TopicCategory());
		form.setNames(tc.getNames());
		form.setEnvalue(tc.getValue());
		form.setStatus(tc.isStatus());
		form.setRecord(id);
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/topic_category/edit";
	}
	@PostMapping(path="/edit")
	public String editAction(
			@ModelAttribute("form")TopicCategoryForm form, 
			HttpServletRequest request, 
			Model model){
		TopicCategory tc = new TopicCategory();
		tc.setNames(form.getNames());
		tc.setValue(form.getEnvalue());
		tc.setStatus(form.getBooleanStatus());
		//
		boolean symbol = false;String errMsg=null;
		try{
			if(form.isUpdate()) {
				symbol = topicCategoryService.edit(form.getIntegerRecord(), tc).orElse(false);
			}else{
				symbol = topicCategoryService.create(tc.getNames(), tc.getValue(), tc.isStatus()).isPresent();
			}
		}catch(IllegalStateException e){
			errMsg=e.getMessage();
		}
		if(symbol){
			return "redirect:/admin/topic/category/";
		}
		model.addAttribute("errors", Commons.optional(errMsg, form.getActionTitle()+"话题类型操作失败"));
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/topic_category/edit";
	}
	
	//删除
	@PostMapping(path="/remove", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public TipMessage removeTagAction(
			@RequestParam("id")int categoryId,
			HttpServletRequest request, 
			Model model){
		boolean symbol = topicCategoryService.remove(categoryId).orElse(false);
		if (symbol) {
			return TipMessage.ofSuccess("话题类型删除成功");
		}
		return TipMessage.ofError("操作失败");
	}
	
	//所有可用的
	@GetMapping(path="/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String,String> getAllBoardForJson(
			HttpServletRequest request, 
			Model model){
		return topicCategoryService.getAllUsed().collect(Collectors.toMap(TopicCategory::getValue, TopicCategory::getNames));
	}
	//指定版块可以发布的话题类型
	@GetMapping(path = "/list.json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public TreeMap<String,String> getBoardTopicCategories(
			@RequestParam("volumes") int boardGroupId, 
			@RequestParam("board") long boardId, 
			HttpServletRequest request, 
			Model model) {
		TreeSet<TopicCategory> categories = new TreeSet<>();
		if(boardGroupId>=0 && boardId>0){
			Supplier<TreeSet<TopicCategory>> supplier = () -> new TreeSet<TopicCategory>(Comparator.comparingLong(TopicCategory::getId));
			categories = boardTopicCategoryIndexService.getAllByBoardTopicCategories(boardGroupId, boardId).collect(Collectors.toCollection(supplier));
		}else{
			categories.add(TopicCategory.empty()); //java.lang.ClassCastException: com.apobates.forum.core.entity.TopicCategory cannot be cast to java.lang.Comparable
		}
		TreeMap<String,String> data = new TreeMap<>();
		for(TopicCategory tc : categories){
			data.put(tc.getValue(), tc.getNames());
		}
		return data;
				//categories.stream().sorted(Comparator.comparingLong(TopicCategory::getId)).collect(Collectors.toMap(TopicCategory::getValue, TopicCategory::getNames));
	}
}
